<?php
namespace extend;

use lib\Session;

class Verify{

    private $image = null;
    private $conf = array(
        'width'    => 220,
        'height'   => 60,
        'code_length'   => 5,
        'font_size'     => 40,
        'is_trouble'    => true,
        'ttf_max'       => 2,
    );
    const FONT_PATH = ROOT_PATH . '/public/resource/ttf/';

    /**
     * Verify constructor.
     * @param array $options
     */
    public function __construct($options = []){
        if(!is_array($options)){ return false; }
        $this->conf = array_merge($this->conf, $options);
    }

    /**
     * 生成验证码
     * @return int
     */
    private function createCode(){
        $code = rand(100000, 999999);
        $code = substr(dechex((int)$code), 0, $this->conf['code_length']);
        Session::set('verify_code', strtolower($code));
        return $code;
    }

    /**
     * 绘制验证码
     */
    public function create(){
        header('Content-Type: image/jpeg');
        $code = str_split($this->createCode());
        $bgRand = round(220, 255);
        $this->image = imagecreatetruecolor($this->conf['width'], $this->conf['height']);
        $background = imagecolorallocate($this->image, 255, 255, $bgRand);
        imagefill($this->image, 0, 0, $background);
        $font = self::FONT_PATH . DS . rand(1, $this->conf['ttf_max']) . '.ttf';
        $marginL = ceil(($this->conf['width'] - $this->conf['code_length'] * $this->conf['font_size']) / 2) - 10;
        $this->conf['is_trouble'] && $this->trouble($code);
        for($i = 0; $i < count($code); $i++){
            $padding = ($this->conf['font_size'] + 5) * $i + $marginL;
            $color = imagecolorallocate($this->image, rand(0, 150), rand(0, 150), rand(0, 150));
            imagettftext($this->image, $this->conf['font_size'], rand(-10, 10), $padding, 47, $color, $font, $code[$i]);
        }
        imagejpeg($this->image);
    }

    /**
     * 制造麻烦
     * @param $code
     */
    private function trouble($code){
        $font = self::FONT_PATH . DS . '1.ttf';
        for($i = 0; $i < $this->conf['width']; $i++){
            $color = imagecolorallocate($this->image, rand(0, 150), rand(0, 150), rand(0, 150));
            $i % 10 == 0 && imagettftext($this->image, 14, rand(-360, 360), rand(0, $this->conf['width'])
                , rand(0, $this->conf['height']), $color, $font, array_rand($code));
        }
    }

    /**
     * 验证码确认
     * @param $code
     * @return bool
     */
    public static function check($code){
        if(strtolower($code) == Session::get('verify_code')){
            Session::remove('verify_code');      //注销该验证码
            return true;
        }else{
            return false;
        }
    }

    /**
     * 析构方法
     */
    public function __destruct(){
        is_resource($this->image) && imagedestroy($this->image);
    }

}